import React, { Component } from 'react';
import styles from './index.module.scss';
import { withRouter } from 'next/router';
import router from 'next/router';

import { withTranslation } from 'next-i18next';
import env from '@/consts/environment';

import ep from '@/utils/eventproxy';
import { connect } from 'react-redux';
import { update } from '@/utils/immutableUtil';
import Eventproxy from 'eventproxy';
import { Context } from './context';
import { initEvent } from './event';
import Socket from './socket';

import Left from './Left';
import Right from './Right';

import { motion } from 'framer-motion';
import { v1 as uuidv1 } from 'uuid';

@withTranslation('common')
@withRouter
@connect(({}) => ({}))
class Comp extends Component {
  controller = {};
  state = {
    // 事件对象
    event: new Eventproxy(),
    show: true,
  };

  componentDidMount() {
    this.init();
  }

  componentWillUnmount = () => {
    ep.removeListener('headerNewChat', this.headerNewChat);
    this.props.dispatch({ type: 'ppt/init' });
  };

  // 初始化
  init = async () => {
    const { event } = this.state;
    initEvent(event, this);
    ep.on('headerNewChat', this.headerNewChat);
    this.scrollToBottom();
  };

  headerNewChat = () => {
    const { event } = this.state;
    
    this.setState({ show: false }, () => {
      this.setState({ show: true });
      event.emit('newChat');
    });
  };

  changeState = (obj) => {
    this.props.dispatch({
      type: 'ppt/setState',
      payload: obj,
    });
  };

  // 设置组件控制器
  setController = (name, compThis) => {
    this.controller[name] = compThis;
  };

  //输入框选中
  inputFocus = () => {
    const controller = this.controller;
    if (controller.ChatInput) {
      controller.ChatInput?.textareaRef?.current?.focus();
    }
  };

  // 调用js沙箱
  getSandbox = async (fragment) => {
    var apiKey = process.env.e2bApiKey;
    var str = window.localStorage.getItem('e2bApiKey');
    if (str) apiKey = str;
    var url = '/nextApi/sandbox';

    if (router.basePath != '/') {
      url = `${router.basePath}/api/sandbox`;
    }

    const response = await fetch(url, {
      method: 'POST',
      body: JSON.stringify({
        fragment: fragment,
        userID: '1111',
        apiKey: apiKey,
      }),
    });
    return response;
  };

  // 滚动到底部
  scrollToBottom = () => {
    const chatContainer = document.getElementById('chat-container');
    if (!chatContainer) return;
    chatContainer.scrollTop = chatContainer.scrollHeight;
  };

  // 滚动到底部 (平滑)
  scrollToBottom2 = () => {
    // 获取目标 div 元素
    const divElement = document.getElementById('chat-container-cont');
    if (!divElement) return;

    // 获取 div 内最后一个子元素
    const lastChild = divElement.lastElementChild;

    // 如果有子元素，则滚动到最后一个子元素
    if (lastChild) {
      lastChild.scrollIntoView({
        behavior: 'smooth', // 平滑滚动，可选 'auto'
        block: 'end', // 滚动到元素底部
      });
    }
  };

  // 设置侧边栏
  setSidebar = (val) => {
    this.props.dispatch({
      type: 'global/setState',
      payload: { sidebarOpen: val },
    });

    if (val) {
      window.localStorage.setItem('sidebarOpen', val);
    } else {
      window.localStorage.removeItem('sidebarOpen');
    }
  };

  initWs = () => {
    this.closeWs()
    var client_id = uuidv1();

    var apiHost = env.apiHost;
    var str = window.localStorage.getItem('apiHost');
    if (str) apiHost = str;

    var url = `ws://${apiHost}?client_id=${client_id}`;
    var ws = new Socket({ url: url, uuid: client_id });
    window.ws = ws;
  };

  closeWs = ()=>{
    if (window.ws) {
      window.ws.close();
      window.ws = null;
    }
  }

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  render() {
    // Context 全局参数 （所有后代都可获取调用）
    var store = {
      ...this.state,
      controller: this.controller,
      changeState: this.changeState,
      setController: this.setController,
      inputFocus: this.inputFocus,
      scrollToBottom: this.scrollToBottom,
      scrollToBottom2: this.scrollToBottom2,
      getSandbox: this.getSandbox,
      setSidebar: this.setSidebar,
      initWs: this.initWs,
      closeWs: this.closeWs,
    };

    const { show } = this.state;
    return (
      <Context.Provider value={store}>
        {show && (
          <motion.div
            initial={{ opacity: 0 }} // 初始状态：不透明度为 0
            animate={{ opacity: 1 }} // 动画状态：不透明度为 1
            transition={{ duration: 1 }} // 动画持续时间为 1 秒
            style={{ height: '100%' }}
          >
            <div className={styles.pageCont}>
              <Left
                init={(This) => {
                  this.setController('Left', This);
                }}
              />

              <Right />
            </div>
          </motion.div>
        )}
      </Context.Provider>
    );
  }
}

export default Comp;
